 //
//  gerenbumenViewController.m
//  shuilijuOASystem
//
//  Created by michael on 16/10/26.
//  Copyright © 2016年 czd. All rights reserved.
//
#import "bumenTableViewCell.h"

#import "gerenbumenViewController.h"

@interface gerenbumenViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,copy)NSString * searchText;

@end

@implementation gerenbumenViewController
-(NSMutableArray*)contentsArray{

    if (_contentsArray == nil) {
        _contentsArray =   [NSMutableArray array];
    }
    
    return _contentsArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view .backgroundColor = [UIColor whiteColor];
    self.title = @"个人通讯录";
    _tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
    __weak typeof(self) weakSelf = self;
   
    self.currentPage = 1;

        [self setRightItem];
 [self.tableView addHeaderWithCallback:^{
        weakSelf.currentPage = 1;
if (weakSelf.isNeedRefresh) {
    [weakSelf loadSearchMore];

}else{
[weakSelf requestData];
 }
    }];
    [self.tableView headerBeginRefreshing];

    
        [self.tableView addFooterWithCallback:^{
            if ((self.currentPage - 1)*KPageSize < self.totalNumber) {
            
            
            if (weakSelf.isNeedRefresh) {
                [weakSelf loadSearchMore];
    
}else{
                 [weakSelf requestMoreData];
                 }
            }else{
                [weakSelf.view.window makeToast:@"没有更多数据了"];
                [weakSelf.tableView footerEndRefreshing];
            }
           
        }];
//    }
}


-(void)setRightItem{
    UIBarButtonItem * rightitem = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searchAction)];
    self.navigationItem.rightBarButtonItem = rightitem;
}

-(void)searchAction{

    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"搜索通讯录" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alertView.delegate = self;
    alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField * textField = [alertView textFieldAtIndex:0];
    textField.placeholder = @"请输入关键字";
    [alertView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (buttonIndex == 1) {
        UITextField * textField = [alertView textFieldAtIndex:0];
        if (textField.text.length == 0) {
            return;
        }
        [_contents mutableCopy];
                        [self.contentsArray  removeAllObjects];

    _isNeedRefresh = YES;
  self.currentPage = 1;

    [self loadSearchData:textField.text];

       
}
    
}
-(void)loadSearchData:(NSString*)text{
    NSString * method = nil;
    self.searchText = text;
            method = @"personalSearch";
    
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"query":text},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    __weak typeof(self) weakSelf = self;
   [HttpTools requestWithURL:@"exchtxl" arrays:array method:method success:^(id JSON) {
        if (self.currentPage == 1) {
            [self.contentsArray removeAllObjects];
        }
       
 _contentsArray = JSON[@"data"];
        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
        
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
        
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];
    
    
}

//搜索内容加载更多
- (void)loadSearchMore
{
 NSString * method = nil;
 //   self.searchText = text;
           method = @"personalSearch";
 
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"query":_searchText},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    __weak typeof(self) weakSelf = self;
//    [HttpTools requestWithURL:@"exchSearch" arrays:array method:method success:^(id JSON) {
   [HttpTools requestWithURL:@"exchtxl" arrays:array method:method success:^(id JSON) {

      
 _contentsArray = JSON[@"data"];
        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
        
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
        
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];
    
    
}


//请求数据
-(void)requestData{
    [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];

          NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];

 [HttpTools requestWithURL:@"exchtxl" arrays:array method:@"personalPage" success:^(id JSON) {

        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
                [self.tableView headerEndRefreshing];
//                _contentsArray = [NSMutableArray array];
for (NSDictionary *dic in JSON[@"data"]) {
    [_contentsArray addObject:dic];
}
//        _tempArray = JSON[@"data"];
        self.currentPage++;

               [self.tableView reloadData];
    } failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
    }];

    
}
//加载更多
-(void)requestMoreData{
   [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];

          NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
 [HttpTools requestWithURL:@"exchtxl" arrays:array method:@"personalPage" success:^(id JSON) {

       [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
        _contentsArray = JSON[@"data"];
               [self.tableView reloadData];
        self.currentPage++;

    } failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
    }];

    
    
}


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

     static NSString * cellIdentifier = @"cellId";
     
            bumenTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {
                cell = [[bumenTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
    NSDictionary *dict = self.contentsArray[indexPath.row];
    cell.dict = dict;

    return cell;
}

    

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.contentsArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
     NSDictionary * dict = self.contentsArray[indexPath.row];

//    UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//    OADepAddressController * depVC = (OADepAddressController*)[storyBoard instantiateViewControllerWithIdentifier:@"DepAddressID" ];
//    depVC.path = dict[@"unid"];
//    [self.navigationController pushViewController:depVC animated:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
